const { formatXml } = require('../utils/format')
const customerService = require('../controller/customerService')
const { deductBalance, findUser, getBalance } = require("../model/user")
const getCompletions = require("../controller/openai")


async function messageController(req, res, next) {
  //消息微信发送过来的消息
  const message = formatXml(req.body.xml)

  //回复消息
  const { tousername, fromusername } = message
  const prompt = message.recognition ? message.recognition : message.content
  //生成消息发送时间
  const createTime = new Date().getTime()
  // 定义发送消息的内容体
  let content = ''

  //获取用户的会话模式
  const model = (await findUser(fromusername)).model

  //根据用户的会话模型，来做不同的消息回复
  if (model === 'chatgpt') {

    const balance = await getBalance(fromusername)
    if (balance > 0) {
      //只有ChatGPT服务的时候才定义
      content = '请等待chatgpt消息返回...'
      //回复消息
      res.render('reply', {
        tousername,
        fromusername,
        createTime,
        content
      })
      //用户账户金额扣除
      await deductBalance(fromusername)

      // 从 OpenAI API 里获取数据
      const completion = await getCompletions(prompt)
      // content = '来源于ChatGPT的回答。'

      //客服回复消息
      await customerService(fromusername, completion)

    } else {
      content = '您的余额不足，请充值！'
      //回复消息
      res.render('reply', {
        tousername,
        fromusername,
        createTime,
        content
      })
    }
  } else {
    content = '目前坐席忙，请等待回复。'
    res.render('reply', {
      tousername,
      fromusername,
      createTime,
      content
    })
  }
}

module.exports = messageController